<template>
  <div class="user-page">
    <div class="container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="user-content">
        <el-row :gutter="30">
          <!-- 左侧用户信息 -->
          <el-col :span="8">
            <el-card class="user-card">
              <div class="user-avatar">
                <el-avatar :size="100" :src="userStore.userInfo?.avatar">
                  {{ userStore.userInfo?.nickname?.charAt(0) || userStore.userInfo?.username?.charAt(0) }}
                </el-avatar>
              </div>
              
              <div class="user-info">
                <h2>{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}</h2>
                <p class="username">@{{ userStore.userInfo?.username }}</p>
                <p class="user-id">用户ID: {{ userStore.userInfo?.id }}</p>
              </div>

              <div class="user-actions">
                <el-button type="primary" @click="showEditDialog = true">
                  编辑资料
                </el-button>
                <el-button @click="handleLogout" type="danger">
                  退出登录
                </el-button>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧详细信息 -->
          <el-col :span="16">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="用户信息" name="info">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>用户详细信息</span>
                    </div>
                  </template>
                  <el-descriptions :column="2" border>
                    <el-descriptions-item label="用户名">
                      {{ userStore.userInfo?.username }}
                    </el-descriptions-item>
                    <el-descriptions-item label="昵称">
                      {{ userStore.userInfo?.nickname || '未设置' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="邮箱">
                      {{ userStore.userInfo?.email || '未设置' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="手机号">
                      {{ userStore.userInfo?.phone || '未设置' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <el-tag :type="userStore.userInfo?.status === 1 ? 'success' : 'danger'">
                        {{ userStore.userInfo?.status === 1 ? '正常' : '禁用' }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="注册时间">
                      {{ formatDate(userStore.userInfo?.createTime) }}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
                <!-- 购物车统计 -->
                <el-card style="margin-top: 20px;">
                  <template #header>
                    <div class="card-header">
                      <span>购物车统计</span>
                    </div>
                  </template>
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <div class="stat-item">
                        <div class="stat-number">{{ cartStore.totalCount }}</div>
                        <div class="stat-label">购物车商品数</div>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="stat-item">
                        <div class="stat-number">{{ cartStore.cartItems.length }}</div>
                        <div class="stat-label">商品种类</div>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="stat-item">
                        <div class="stat-number">¥{{ cartStore.totalPrice.toFixed(2) }}</div>
                        <div class="stat-label">购物车总价</div>
                      </div>
                    </el-col>
                  </el-row>
                </el-card>
              </el-tab-pane>
              <el-tab-pane label="我的订单" name="orders">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>我的订单</span>
                    </div>
                  </template>
                  <el-table :data="orderList" border stripe v-loading="orderLoading">
                    <el-table-column prop="id" label="订单号" width="120">
                      <template #default="scope">
                        <el-link type="primary" @click="goToOrderDetail(scope.row.id)">{{ scope.row.id }}</el-link>
                      </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="下单时间" width="180">
                      <template #default="scope">
                        {{ formatDate(scope.row.createTime) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="totalPrice" label="总价" width="100">
                      <template #default="scope">
                        ¥{{ scope.row.totalPrice }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="scope">
                        <el-tag :type="statusTagType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                      <template #default="scope">
                        <el-button type="text" @click="goToOrderDetail(scope.row.id)">详情</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty v-if="!orderLoading && orderList.length === 0" description="暂无订单" />
                </el-card>
              </el-tab-pane>
              <el-tab-pane label="秒杀订单" name="seckill">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>我的秒杀订单</span>
                    </div>
                  </template>
                  <el-table :data="seckillOrderList" border stripe v-loading="seckillOrderLoading">
                    <el-table-column prop="id" label="订单号" width="120" />
                    <el-table-column prop="name" label="商品名称" />
                    <el-table-column prop="price" label="秒杀价" width="100">
                      <template #default="scope">¥{{ scope.row.price }}</template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="scope">
                        <el-tag :type="statusTagType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="createdTime" label="下单时间" width="180">
                      <template #default="scope">{{ formatDate(scope.row.createdTime) }}</template>
                    </el-table-column>
                    <el-table-column label="操作" width="220">
                      <template #default="scope">
                        <el-button v-if="scope.row.status === 0" type="primary" size="small" @click="handleSeckillOrderAction(scope.row, 'pay')">支付</el-button>
                        <el-button v-if="scope.row.status === 0" type="danger" size="small" @click="handleSeckillOrderAction(scope.row, 'cancel')">取消</el-button>
                        <el-button v-if="scope.row.status === 1" type="warning" size="small" @click="handleSeckillOrderAction(scope.row, 'refund')">退款</el-button>
                        <el-button v-if="scope.row.status === 2" type="success" size="small" @click="handleSeckillOrderAction(scope.row, 'complete')">完成</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty v-if="!seckillOrderLoading && seckillOrderList.length === 0" description="暂无秒杀订单" />
                </el-card>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>

      <!-- 编辑用户信息对话框 -->
      <el-dialog
        v-model="showEditDialog"
        title="编辑用户信息"
        width="500px"
        @close="resetEditForm"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editRules"
          label-width="80px"
        >
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showEditDialog = false">取消</el-button>
            <el-button type="primary" @click="handleUpdateUser" :loading="updating">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { getMyOrders } from '@/api/order'
import { getSeckillOrderList, paySeckillOrder, cancelSeckillOrder, refundSeckillOrder, completeSeckillOrder } from '@/api/seckill'
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateUser } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const showEditDialog = ref(false)
const updating = ref(false)
const editFormRef = ref()
// activeTab 支持通过路由参数初始化
const activeTab = ref(route.query.tab || 'info')
const orderList = ref([])
const orderLoading = ref(false)
const seckillOrderList = ref([])
const seckillOrderLoading = ref(false)

const editForm = reactive({
  id: '',
  nickname: '',
  email: '',
  phone: ''
})

// 验证规则
const validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(value)) {
      callback(new Error('请输入正确的邮箱格式'))
    } else {
      callback()
    }
  }
}

const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入正确的手机号格式'))
    } else {
      callback()
    }
  }
}

const editRules = {
  nickname: [
    { max: 20, message: '昵称长度不能超过 20 个字符', trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ]
}

// 方法
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
    }
  }
}

const resetEditForm = () => {
  if (userStore.userInfo) {
    editForm.id = userStore.userInfo.id
    editForm.nickname = userStore.userInfo.nickname || ''
    editForm.email = userStore.userInfo.email || ''
    editForm.phone = userStore.userInfo.phone || ''
  }
}

const handleUpdateUser = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    updating.value = true

    const response = await updateUser(editForm)
    
    if (response.data) {
      // 更新本地用户信息
      userStore.setUserInfo(response.data)
      ElMessage.success('更新成功')
      showEditDialog.value = false
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error(error.message || '更新失败')
  } finally {
    updating.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

const fetchOrders = async () => {
  if (!userStore.userInfo?.id) return
  orderLoading.value = true
  try {
    const response = await getMyOrders(userStore.userInfo.id)
    if (response.data) {
      orderList.value = response.data
    }
  } finally {
    orderLoading.value = false
  }
}

const goToOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

const statusText = (status) => {
  switch (status) {
    case 0: return '待支付'
    case 1: return '已支付'
    case 2: return '已发货'
    case 3: return '已完成'
    case 4: return '已取消'
    default: return '未知'
  }
}
const statusTagType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'success'
    case 4: return 'danger'
    default: return 'info'
  }
}

const fetchSeckillOrders = async () => {
  seckillOrderLoading.value = true
  try {
    const response = await getSeckillOrderList()
    console.log('秒杀订单接口返回：', response.data)
    if (response.data) {
      seckillOrderList.value = response.data
      console.log('赋值后seckillOrderList:', seckillOrderList.value)
    }
  } finally {
    seckillOrderLoading.value = false
  }
}

const handleSeckillOrderAction = async (order, action) => {
  let fn, msg
  if (action === 'pay') { fn = paySeckillOrder; msg = '支付' }
  if (action === 'cancel') { fn = cancelSeckillOrder; msg = '取消' }
  if (action === 'refund') { fn = refundSeckillOrder; msg = '退款' }
  if (action === 'complete') { fn = completeSeckillOrder; msg = '完成' }
  try {
    const res = await fn(order.id)
    if (res.code === 200) {
      ElMessage.success(msg + '成功')
      fetchSeckillOrders()
    } else {
      ElMessage.error(res.message || (msg + '失败'))
    }
  } catch (e) {
    ElMessage.error(msg + '失败')
  }
}

// 监听路由参数变化，自动切换Tab
watch(() => route.query.tab, (newTab) => {
  if (newTab) activeTab.value = newTab
})
// 监听Tab切换，切到秒杀订单时刷新
watch(activeTab, (tab) => {
  if (tab === 'seckill') {
    fetchSeckillOrders()
  }
})

// 生命周期
onMounted(() => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  resetEditForm()
  cartStore.fetchCartItems()
  fetchOrders()
  fetchSeckillOrders()
})
</script>

<style scoped>
.user-page {
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin-bottom: 30px;
}

.user-content {
  margin-top: 20px;
}

.user-card {
  text-align: center;
  padding: 30px 20px;
}

.user-avatar {
  margin-bottom: 20px;
}

.user-info {
  margin-bottom: 30px;
}

.user-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #333;
}

.username {
  margin: 0 0 5px 0;
  color: #666;
  font-size: 14px;
}

.user-id {
  margin: 0;
  color: #999;
  font-size: 12px;
}

.user-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.user-actions .el-button {
  width: 100%;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

@media (max-width: 768px) {
  .user-content .el-row {
    flex-direction: column;
  }
  
  .user-content .el-col {
    width: 100% !important;
    margin-bottom: 20px;
  }
}
</style> 